package com.lagou.web;

import com.lagou.domain.AdminUser;
import com.lagou.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 登录控制器
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if ("" != username && "" != password) {
            AdminUser adminUser = new AdminUser(username, password);

            // 判断用户是否存在
            if (LoginService.check(adminUser)) {
                // 如果存在设置session
                HttpSession session = req.getSession();
                session.setAttribute("USER", username);

                // 添加cookie
                Cookie cookie = new Cookie("USER", username);
                resp.addCookie(cookie);

                // 重定向到登录成功页面
                resp.sendRedirect("login/success.html");
            } else {
                resp.getWriter().write("用户名或密码错误");
            }
        } else {
            resp.getWriter().write("请填写用户名和密码");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
